<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    body {
      padding: 100px;
    }
  </style>
</head>
<body>
<canvas id="canvas" width="300" height="200"></canvas>
<div style="width: 100px; height: 100px;" id="screen"></div>
<script>
  const $canvas = document.querySelector('#canvas');
  const $screen = document.querySelector('#screen');
  const ctx = $canvas.getContext('2d');

  $canvas.width = 300;
  $canvas.height = 200;

  ctx.clearRect(0, 0, $canvas.width, $canvas.height);

  var hGrad = ctx.createLinearGradient(0, 0, $canvas.width, 0);
  hGrad.addColorStop(0 / 6, '#F00');
  hGrad.addColorStop(1 / 6, '#FF0');
  hGrad.addColorStop(2 / 6, '#0F0');
  hGrad.addColorStop(3 / 6, '#0FF');
  hGrad.addColorStop(4 / 6, '#00F');
  hGrad.addColorStop(5 / 6, '#F0F');
  hGrad.addColorStop(6 / 6, '#F00');

  // 673ab7
  ctx.fillStyle = hGrad;
  ctx.fillRect(0, 0, $canvas.width, $canvas.height);

  var vGrad = ctx.createLinearGradient(0, 0, 0, $canvas.height);
  switch ('s') {
    case 's': // 从纯色到纯白色
      vGrad.addColorStop(0, 'rgba(255,255,255,0)');
      vGrad.addColorStop(1, 'rgba(255,255,255,1)');
      break;
    case 'v': // 从纯色到纯黑色
      vGrad.addColorStop(0, 'rgba(0,0,0,0)');
      vGrad.addColorStop(1, 'rgba(0,0,0,1)');
      break;
  }
  ctx.fillStyle = vGrad;
  ctx.fillRect(0, 0, $canvas.width, $canvas.height);

  $canvas.addEventListener('click', (ev) => {
    console.log(ev)
    console.log(`client(x: ${ev.clientX}, y: ${ev.clientY})`);
    console.log(`page(x: ${ev.pageX}, y: ${ev.pageY})`);
    console.log(`layer(x: ${ev.layerX}, y: ${ev.layerY})`);
    console.log(`offset(x: ${ev.offsetX}, y: ${ev.offsetY})`);
    console.log(ctx.getImageData(ev.offsetX, ev.offsetY, 1, 1));

    const [r, g, b, a] = ctx.getImageData(ev.offsetX, ev.offsetY, 1, 1).data;
    $screen.style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a})`
  }, false);

  function mouseMove (ev) {
    const [r, g, b, a] = ctx.getImageData(ev.offsetX, ev.offsetY, 1, 1).data;
    $screen.style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a})`
  }

  $canvas.addEventListener('mousedown', (ev) => {
    const [r, g, b, a] = ctx.getImageData(ev.offsetX, ev.offsetY, 1, 1).data;
    $screen.style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a})`
    $canvas.addEventListener('mousemove', mouseMove, false);
  }, false);

  $canvas.addEventListener('mouseup', (ev) => {
    const [r, g, b, a] = ctx.getImageData(ev.offsetX, ev.offsetY, 1, 1).data;
    $screen.style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a})`
    $canvas.removeEventListener('mousemove', mouseMove, false);
  }, false);

  $canvas.addEventListener('mouseout', (ev) => {
    console.log('mouseout')
    $canvas.removeEventListener('mousemove', mouseMove, false);
  }, false);

</script>
</body>
</html>